/*
  Programa GEFE - Gestión de eventos lúdicos.
  Copyright (C) 2010  Antonio Ramírez Marti

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "fichasdialog.h"
#include "ui_fichasdialog.h"
#include <QDate>
#include <QMessageBox>
#include <QDebug>

FichasDialog::FichasDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::FichasDialog)
{
    ui->setupUi(this);
    setup();
}

FichasDialog::~FichasDialog()
{
    if(modelo)
        delete modelo;
    if(modeloSalas)
        delete modeloSalas;
    delete ui;
}

void FichasDialog::changeEvent(QEvent *e)
{
    QDialog::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void FichasDialog::setup()
{
    modelo=0;
    modeloSalas=0;
    this->preparaModelo();
    this->preparaDias();
    this->preparaSalas();
    this->preparaSeleccionDirectorio();
    connect(ui->sendButton,SIGNAL(clicked()),this,SLOT(enviar()));
    connect(ui->informeSalasButton,SIGNAL(clicked()),this,SLOT(enviarSala()));
    connect(ui->printButton,SIGNAL(clicked()),this,SLOT(enviarImprimir()));
    connect(ui->printSalasButton,SIGNAL(clicked()),this,SLOT(enviarImprimirSala()));
}

void FichasDialog::preparaDias()
{
    {
        QSqlQuery query(QSqlDatabase::database("evento"));

        query.exec("SELECT DISTINCT dia FROM actividad");

        while(query.next())
            ui->diaComboBox->addItem("Actividades del "+query.value(0).toDate().toString("dddd, 'd'ia dd"),query.value(0));

    }

    connect(ui->diaComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(filtraModelo(int)));
}

void FichasDialog::preparaModelo()
{
    if(modelo)
    {
        delete modelo;
        modelo=0;
    }

    if(modeloSalas)
    {
        delete modeloSalas;
        modeloSalas=0;
    }

    modelo=new ModeloActividades(this,QSqlDatabase::database("evento"));
    modelo->setFilter("estado=0 or estado=1");

    modeloSalas=new ModeloActividades(this,QSqlDatabase::database("evento"));
    modeloSalas->setFilter("estado=0 or estado=1");

    ui->tableView->setModel(modelo);
    ui->vistaSalas->setModel(modeloSalas);

    for(int i=0;i<22;i++)
    {
        ui->tableView->setColumnHidden(i,true);
        ui->vistaSalas->setColumnHidden(i,true);
    }


    ui->tableView->setColumnHidden(1,false);
    ui->tableView->setColumnHidden(9,false);
    ui->tableView->setColumnHidden(10,false);
    ui->tableView->setColumnHidden(11,false);
    ui->tableView->setColumnHidden(14,false);
    ui->tableView->verticalHeader()->setHidden(true);
    ui->tableView->horizontalHeader()->setHidden(true);
    ui->tableView->setAlternatingRowColors(true);

    ui->vistaSalas->setColumnHidden(1,false);
    ui->vistaSalas->setColumnHidden(9,false);
    ui->vistaSalas->setColumnHidden(10,false);
    ui->vistaSalas->setColumnHidden(11,false);
    ui->vistaSalas->setColumnHidden(14,false);

    modelo->select();
    modeloSalas->setSort(9,Qt::AscendingOrder);
    modeloSalas->select();

    ui->tableView->resizeColumnsToContents();
    ui->vistaSalas->resizeColumnsToContents();
}

void FichasDialog::filtraModelo(int index)
{
    if(index==0)        //Todos los dias
        modelo->setFilter("estado=0 or estado=1");

    else
    {
        QString diaSeleccionado=ui->diaComboBox->itemData(index,Qt::UserRole).toString();

        modelo->setFilter(QString("(estado=0 or estado=1) and dia=").append("'")+diaSeleccionado.append("'"));
    }
}

void FichasDialog::preparaSeleccionDirectorio()
{
    connect(ui->directorioButton,SIGNAL(clicked()),this,SLOT(seleccionaDirectorio()));
    connect(ui->dirSalasButton,SIGNAL(clicked()),this,SLOT(seleccionaDirectorioSala()));
}

void FichasDialog::seleccionaDirectorio()
{
    ui->directorioLine->setText(QFileDialog::getExistingDirectory(this,"Directorio de salida de actividades"));
}

void FichasDialog::seleccionaDirectorioSala()
{
    ui->dirSalasLine->setText(QFileDialog::getExistingDirectory(this,"Directorio de salida de informe de sala"));
}

void FichasDialog::enviar()
{
    if(ui->directorioLine->text().isEmpty() || ui->directorioLine->text().isNull())
        QMessageBox::warning(this,"Dialogo de actividades","No se ha seleccionado un directorio de salida. Por favor, seleccione un directorio.",QMessageBox::Ok);

    else
    {
        QSqlQuery query=modelo->query();

        emit this->sendActividades(query,ui->directorioLine->text());
    }
}

void FichasDialog::enviarImprimir()
{
    QSqlQuery query=modelo->query();

    emit this->sendImprimirActividades(query);
}

void FichasDialog::enviarSala()
{
    if(ui->dirSalasLine->text().isEmpty()|| ui->dirSalasLine->text().isNull())
        QMessageBox::warning(this,"Dialogo de actividades","No se ha seleccionado un directorio de salida. Por favor, seleccione un directorio.",QMessageBox::Ok);
    else
    {
        QSqlQuery query;
        query=modeloSalas->query();

        if(ui->salasComboBox->currentIndex())
            emit this->sendSala(query,ui->salasComboBox->currentText(),ui->dirSalasLine->text());
        else
        {
            QSqlQuery *aux;

            for(int i=1;i<ui->salasComboBox->count();i++)
            {
                aux=new QSqlQuery(QSqlDatabase::database("evento"));

                aux->prepare("SELECT * from actividad where (estado=0 or estado=1) and localizacion=:sala order by dia,horaInicio asc");

                aux->bindValue(":sala",ui->salasComboBox->itemText(i));
                aux->exec();
                emit this->sendSala(*aux,ui->salasComboBox->itemText(i),ui->dirSalasLine->text());
            }
        }
    }
}

void FichasDialog::enviarImprimirSala()
{
    QPrinter *impresora=new QPrinter();
    QPrintDialog *dialog=new QPrintDialog(impresora,this);

    if(dialog->exec()==QDialog::Accepted)
    {
            QSqlQuery query;
            query=modeloSalas->query();

            if(ui->salasComboBox->currentIndex())
                emit this->sendSalaImprimir(query,ui->salasComboBox->currentText(),impresora);
            else
            {
                QSqlQuery *aux;

                for(int i=1;i<ui->salasComboBox->count();i++)
                {
                    aux=new QSqlQuery(QSqlDatabase::database("evento"));

                    aux->prepare("SELECT * from actividad where (estado=0 or estado=1) and localizacion=:sala order by dia,horaInicio asc");

                    aux->bindValue(":sala",ui->salasComboBox->itemText(i));
                    aux->exec();
                    emit this->sendSalaImprimir(*aux,ui->salasComboBox->itemText(i),impresora);
                }
            }
    }
}

void FichasDialog::preparaSalas()
{
    {
        QSqlQuery query(QSqlDatabase::database("evento"));

        query.exec("SELECT nombre FROM lugar order by nombre ASC");

        while(query.next())
            ui->salasComboBox->addItem(query.value(0).toString(),query.value(0));

    }

    connect(ui->salasComboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(filtraModeloSalas(int)));
}

void FichasDialog::filtraModeloSalas(int sala)
{
    if(!sala)        //Todos los dias
        modeloSalas->setFilter("estado=0 or estado=1");

    else
    {
        QString salaActual=ui->salasComboBox->itemData(sala,Qt::UserRole).toString();

        modeloSalas->setFilter(QString("(estado=0 or estado=1) and localizacion=")+salaActual.append("'").prepend("'"));
    }
}
